package com.app.components
{
	import com.app.base.Component;
	import com.greensock.TweenMax;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.filters.DropShadowFilter;
	import flash.geom.Rectangle;
	
	[Event(name="complete", type="flash.events.Event")]
	public class Navigator extends Component
	{
		private var _pages:Object = new Object();
		private var _ids:Array=[];
		private var _back:Boolean;
		private var _lastDisplay:DisplayObject;
		private var _currentDisplay:DisplayObject;
		private var _viewRect:Rectangle;
		private var _homeName:String = null;
		private var _moveing:Boolean;
		
		public function Navigator(viewRect:Rectangle)
		{
			super();
			_viewRect = viewRect;
			
			// 加入投影位图
			var bmp:Bitmap = new Bitmap(new DropShadow_Class() as BitmapData);
			addChildAt(bmp ,0);
			bmp.x = -10;
		}
		
		
		/** 加入显示对象 */	
		public function push(pageName:String ,display:DisplayObject):void
		{
			_pages[pageName] = display;
		}
		
		/** 设置首页并显示 */
		public function setHome(pageName:String):void
		{
			_homeName = pageName;
			_currentDisplay = _pages[_homeName];
			addChild(_currentDisplay);
			_currentDisplay.x = _currentDisplay.y = 0;
		}
		
		
		
		
		
		
		/** 返回到首页 并清空返回列表页 */
		public function getHome(value:Boolean):void
		{
			if(_moveing)return;
			if(_currentDisplay==_pages[_homeName])return;
			_ids = [];
			_back = value;
			show(_homeName);
		}
		
		
		/** 返回上一页  */	
		public function back(value:Boolean):void
		{
			if(_moveing)return;
			if(_ids.length>1)
			{
				_back = value;
				_ids.splice(_ids.length-1 ,1);
				show(_ids[_ids.length-1]);
			}
		}
		
		
		/** 显示指定页面 */
		public function show(pageName:String):void
		{
			//判断是否正在换页
			if(_moveing)return;
			
			//判断当前页是否为指定页
			if(_currentDisplay == _pages[pageName])return;
			
			//如果不是返回操作，或跳到主页，则加入到返回列表
			if(_back==false && pageName!=_homeName)_ids.push(pageName);
			
			//判断是否已有页面
			if(_currentDisplay!=null)_lastDisplay = _currentDisplay;
			
			//设置当前页
			_currentDisplay = _pages[pageName];
			addChild(_currentDisplay);
			
			if(_lastDisplay==null)
			{
				_moveing = false;
				_currentDisplay.x = _currentDisplay.y = 0;
			}else{
				_moveing = true;
				_currentDisplay.x = _back==true?-_viewRect.width:_viewRect.width;
				TweenMax.to(_currentDisplay ,.5 ,{x:0});
				TweenMax.to(_lastDisplay ,.5 ,{x:_back==true?_viewRect.width:-_viewRect.width ,onComplete:complete});
			}
			
			_back = false;
		}
		
		private function complete():void
		{
			_moveing = false;
			removeChild(_lastDisplay);
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
	}
}